package com.star.common.oss.factory;

import com.star.common.core.contract.enums.ResultCodeEnum;
import com.star.common.oss.contract.exception.OssException;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽象的oss类型操作类
 *
 * @author zhouhengzhe
 */
@Slf4j
public abstract class AbstractOssTypeServiceFactory implements OssTypeServiceFactory {
    /**
     * 检查对象的所有属性不为空
     *
     * @param obj 对象
     */
    public void checkAllPropertiesNotNull(Object obj) {
        try {
            Class<?> objClass = obj.getClass();
            Field[] fields = objClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value == null) {
                    throw new IllegalAccessException(String.format("Field '%s.%s' is null", objClass.getSimpleName(), field.getName()));
                } else if (value instanceof String && ((String) value).isEmpty()) {
                    throw new IllegalAccessException(String.format("Field '%s.%s' is empty", objClass.getSimpleName(), field.getName()));
                }
            }
        } catch (Exception e) {
            throw new OssException(e);
        }
    }

    /**
     * 检查多个属性不为空
     *
     * @param props 属性
     */
    public void checkProperties(String... props) {
        List<String> emptyProps = new ArrayList<>();
        for (String prop : props) {
            if (prop == null || prop.trim().isEmpty()) {
                emptyProps.add(prop);
            }
        }
        if (!emptyProps.isEmpty()) {
            log.info("Following properties are empty:{} " , String.join(", ", emptyProps));
            throw new OssException(ResultCodeEnum.PARAM_NULL);
        }
    }
}
